<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('book_invitations', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('book_id');
            $table->unsignedBigInteger('inviter_id'); // 邀请人ID
            $table->string('token', 64)->unique(); // 邀请令牌
            $table->timestamp('expires_at'); // 过期时间
            $table->boolean('is_used')->default(false); // 是否已使用
            $table->unsignedBigInteger('used_by')->nullable(); // 使用者ID
            $table->timestamp('used_at')->nullable(); // 使用时间
            $table->timestamps();
            
            $table->foreign('book_id')->references('id')->on('money_books')->onDelete('cascade');
            $table->foreign('inviter_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('used_by')->references('id')->on('users')->onDelete('set null');
            
            $table->index(['token', 'expires_at']);
            $table->index(['book_id', 'is_used']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('book_invitations');
    }
};